#include "List.h"

LTNode* LTBuyNode(LTDataType x)
{
	LTNode* node = (LTNode*)malloc(sizeof(LTNode));
	if (node == NULL)
	{
		perror("malloc");
		exit(1);
	}
		node->val = x;
		node->next = node->prve=node;
		return node;
}

void LTInit01(LTNode** pphead)
{
	*pphead = LTBuyNode(-1);
}

LTNode* LTInit02()
{
	LTNode* node = LTBuyNode(-1);
	return node;
}

void LTPrint(LTNode* phead)
{
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		printf("%d->", pcur->val);
		pcur = pcur->next;
	}
	printf("\n");
}

void LTPushBack(LTNode* phead, LTDataType x)
{
	LTNode* newnode = LTBuyNode(x);
	newnode->next = phead;
	newnode->prve = phead->prve;
	phead->prve->next = newnode;
	phead->prve = newnode;
}

void LTPushFront(LTNode* phead, LTDataType x)
{
	LTNode* newnode = LTBuyNode(x);
	newnode->next = phead->next;
	newnode->prve = phead;
	phead->next->prve = newnode;
	phead->next = newnode;
}

void LTPopBack(LTNode* phead)
{
	assert(phead->next != phead);
	LTNode* del = phead->prve;
	del->prve->next = phead;
	phead->prve= del->prve;
	free(del);
	del = NULL;
}

void LTPopFront(LTNode* phead)
{
	assert(phead->next != phead);
	LTNode* del = phead->next;
	del->next->prve = phead;
	phead->next = del->next;
	free(del);
	del = NULL;
}

LTNode* LTFind(LTNode* phead, LTDataType x)
{
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		if (pcur->val == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}

void LTInsert(LTNode* pos, LTDataType x)
{
	assert(pos);
	LTNode* newnode = LTBuyNode(x);
	newnode->next = pos->next;
	newnode->prve = pos;
	pos->next->prve = newnode;
	pos->next = newnode;
}
void LTErase(LTNode* pos)
{
	assert(pos);
	pos->next->prve=pos->prve;
	pos->prve->next = pos->next;
	free(pos);
	pos = NULL;
}

void LTDestory(LTNode* phead)
{
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		LTNode* next = pcur->next;
		next->prve = phead;
		phead->next = next;
		free(pcur);
		pcur = next;
	}
	free(phead);
	pcur=phead = NULL;
}